package com.atguigu.gmall.auth.service.impl;

import com.atguigu.gmall.auth.properites.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.util.HashMap;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private GmallUmsClient gmallUmsClient;


    /*
     * 构建token的cookie配置和秘钥配置 抽取到配置文件中管理
     * 秘钥构建是需要判断 秘钥文件是否存在，不存在需要重新创建
     */

    /*String priKeyPath = "G:\\MyCode\\Code8\\secretkey\\rsa.pri";
    int expireTime = 60 * 60 * 24 * 30;//分钟
    String cookieName = "GMALL-TOKEN";
    int cookieMaxAge = 60 * 60 * 60 * 24 * 30;//秒*/
    //上述全部封装到cookie.properties统一管理
    @Autowired
    private JwtProperties cookieProperties;

    private PrivateKey privateKey = cookieProperties.getPrivateKey();
    private int expireTime = cookieProperties.getExpireTime();
    private String cookieTokenName = cookieProperties.getCookieTokenName();
    private String cookieNickName = cookieProperties.getCookieNickName();

    @Override
    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        //查询
        try {
            //登录信息的验证
            UserEntity userEntity = gmallUmsClient.checkAccount(loginName, password).getData();
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId", userEntity.getId());
            map.put("username", userEntity.getUsername());
            map.put("ip", IpUtils.getIpAddressAtService(request));//为了防止token被盗取，我们也可以在map中存入客户端的ip地址
            String token = JwtUtils.generateToken(map, privateKey, expireTime);//过期时间一个月

            //存入cookie
            /*Cookie cookie = new Cookie("token", token);
            cookie.setDomain("gmall.com");
            cookie.setPath("/");
            cookie.setMaxAge(24 * 60 * 60);//单位秒 cookie的存活时间，设置之后，cookie会被浏览器持久化
            response.addCookie(cookie);*/
            //以上代码太繁琐，直接使用工具类
            CookieUtils.setCookie(request, response, cookieTokenName, token, expireTime*60);
            //为了前端使用方便，我们再搞一个cookie直接存放昵称
            CookieUtils.setCookie(request, response, cookieNickName, userEntity.getNickname(), expireTime*60);
        } catch (Exception e) {
            throw new GmallException("登录账号或者密码错误");
        }



    }


}
